import axios from "axios"

const endPoint = window.API_URI || "https://ipa2s3.mixmedia.com/";

const STATUS_TASK_DONE = 3;
const STATUS_TASK_FAILED = 4;

const http = axios.create({
    baseURL: endPoint
});
const timeoutID = 0;
const maxCounter = 3600; //1 hour
let processCallback = null,
    doneCallback = null,
    failedCallback = null,
    counter = 0;

const checkerCallback = {
    onProcess(callback) {
        processCallback = callback;
        return checkerCallback;
    },
    onDone(callback) {
        doneCallback = callback;
        return checkerCallback;
    },
    onFailed(callback) {
        failedCallback = callback;
        return checkerCallback;
    }
};

function checkResult(task_id) {
    http.get("/task", {
        params: {
            id: task_id
        }
    })
        .then((resp) => {
            let json = resp.data,
                result = (json instanceof String) ? JSON.parse(json) : json;

            if (result && result.status && result.status == 200) {
                const task = result.task || {},
                    status = task.status || 0,
                    url = task.data || "",
                    comment = task.remark || "";

                if (status == STATUS_TASK_DONE) {
                    clearTimeout(timeoutID);
                    if (doneCallback) {
                        doneCallback(url);
                    }
                    return;
                }
                if (status == STATUS_TASK_FAILED) {
                    clearTimeout(timeoutID);
                    if (failedCallback) {
                        failedCallback(comment);
                    }
                    return;
                }

                if (processCallback) {
                    processCallback(comment)
                }

                if (counter >= maxCounter) {
                    failedCallback(`timeout`);
                    return;
                }

                setTimeout(() => {
                    checkResult(task_id)
                }, 1000);
            }
        });
    counter++;
}

export default {
    submit(url, email) {
        let args = {
            url
        };

        if (email && email.length > 0) {
            args['email'] = email
        }

        return http.get("/upload", {
            params: args
        }).then((resp) => {
            let json = resp.data,
                result = (json instanceof String) ? JSON.parse(json) : json;

            if (result && result.status && result.status == 200) {
                return Promise.resolve(result.task_id);
            }
            return Promise.reject()
        })
    },
    getResult(taskID) {
        checkResult(taskID);

        return checkerCallback;
    },
    getOSSParams(filename) {
        return http.get("/oss/upload", {
            params: {
                filename
            }
        }).then((resp) => {
            let json = resp.data,
                result = (json instanceof String) ? JSON.parse(json) : json;

            if (result && result.status && result.status == 200) {
                return Promise.resolve(result.data);
            }
            return Promise.reject()
        })
    },
    submitOSS(params, email) {
        let apiURI = "/oss/submit";

        let args = Object.keys(params).map((key) => {
            return {
                kind: key,
                url: params[key]
            };
        });

        if (email && email.length > 0) {
            apiURI += `?email=${email}`
        }

        return http.post(apiURI, args).then((resp) => {
            const json = resp.data,
                result = (json instanceof String) ? JSON.parse(json) : json;

            if (result && result.status && result.status == 200) {
                return Promise.resolve(result.task_id);
            }
            return Promise.reject()
        })
    },
    readme() {
        return http.get("/ui/readme.md")
            .then((resp) => {
                return Promise.resolve(resp.data);
            })
    }
}